<template>
  <div class="user-container">
    <!-- 头部导航区 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right"> -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item >用户管理</el-breadcrumb-item>
      <el-breadcrumb-item >用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表展示区 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 头部搜索区域 -->
      <div slot="header">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-input placeholder="请输入姓名" v-model="userListQueryObj.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2" :offset="0">
            <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 表格数据 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template v-slot="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="updateUserStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <el-tooltip content="修改" placement="top" effect="dark" :enterable="false">
              <el-button @click="editUserinfo(scope.row.id)" size="mini" type="primary" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="dark" :enterable="false">
              <el-button @click="delUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip content="修改权限" placement="top" effect="dark" :enterable="false">
              <el-button @click="setUser(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userListQueryObj.pagenum"
        :page-sizes="[1, 2, 5, 10, 20, 50]"
        :page-size="userListQueryObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="60%"
      @close="addUserDialogColsed">
      <!-- 添加表单 -->
      <span>
        <el-form :model="addUserForm" :rules="addRules" ref="addRuleFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 按钮组 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
        
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="60%"
      @close="editUserDialogColsed">
      <!-- 添加表单 -->
      <span>
        <el-form :model="editUserForm" :rules="editRules" ref="editUserFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 按钮组 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import rules from '@/general/rules.js'
export default {
  data () {
    return {
      addUserDialogVisible: false,//控制添加用户对话框是否显示,默认不显示
      editUserDialogVisible: false,
      addUserForm: { // 添加用户数据对象
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRules: { // 添加用户校验规则
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '用户名在 3 到 10 个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '密码在 6 到 15 个字符之间', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: rules.FormValidate.Form().validateEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: rules.FormValidate.Form().validatePhone, trigger: 'blur'}
        ]
      },
      // 修改用户信息
      editUserForm: {
        email: '',
        mobile: ''
      },
      // 修改用户校验规则
      editRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: rules.FormValidate.Form().validateEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: rules.FormValidate.Form().validatePhone, trigger: 'blur'}
        ]
      },
      userList: [],
      total: 0,
      userListQueryObj: {
        query: '',
        pagenum: 1,
        pagesize: 2
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 修改用户权限
    setUser (id) {
      console.log(id)
    },
    // 删除用户
    delUser (id) {
      // console.log(id)
      this.$showMessageBox('此操作将永久删除用户,确定删除吗?', async () => {
        console.log('确定删除')
        // 调用接口进行删除
        const {data: res} = await this.$axios.delete(`users/${id}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 重置页码
        this.userListQueryObj.pagenum = 1
        // 刷新页面
        this.getUserList()
        // 提示用户删除成功
        this.$message.success('删除用户成功')
      })
    },
    // 修改用户信息
    editUser () {
      this.$refs.editUserFormRef.validate(async valid =>{
        if (!valid) return this.$message.error('表单数据不合法!!!')
        const {data: res} = await this.$axios.put(`users/${this.editUserForm.id}`, this.editUserForm)
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getUserList()
        this.editUserDialogVisible = false
      })
    },
    // 显示修改用户信息弹窗
    async editUserinfo (id) {
      // 打开弹窗
      this.editUserDialogVisible = true
      // 根据id查询用户信息
      const {data: res} = await this.$axios.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 存储用户信息
      this.editUserForm = res.data
      this.$message.success('获取用户信息成功!')
    },
    // 修改用户信息的表单重置
    editUserDialogColsed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addRuleFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return this.$message.error('表单数据不完整')
        // 添加用户
        const {data: res} = await this.$axios.post('users', this.addUserForm)
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('用户添加成功')
        // 隐藏添加对话框
        this.addUserDialogVisible = false
        // 刷新数据
        this.getUserList()
      })
    },
    // 监听添加用户对话框关闭
    addUserDialogColsed () {
      // 重置表单数据
      this.$refs.addRuleFormRef.resetFields()
    },
    // 获取用户列表数据
    async getUserList () {
      const {data: res} = await this.$axios.get('users', {params: this.userListQueryObj})
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改用户状态
    async updateUserStatus (userInfo) {
      // console.log(userInfo);
      const {data: res} = await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !==200) {
        // 重置本地状态
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 监听 page-sizes 每页显示多少条
    handleSizeChange (newSize) {
      // 当newSize发生变化的时候
      this.userListQueryObj.pagesize = newSize
      // 发起请求
      this.getUserList()
    },
    // 监听当前是第几页 
    handleCurrentChange (curpage) {
      console.log(curpage);
      this.userListQueryObj.pagenum = curpage
      this.getUserList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
